package top.atcra.rpc.compress.impl;

import lombok.extern.slf4j.Slf4j;
import top.atcra.rpc.compress.Compressor;
import top.atcra.rpc.exception.CompressException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class GzipCompressor implements Compressor {
    private static final int BUFFER_SIZE = 4096;

    @Override
    public byte[] compress(byte[] data) {
        if (data == null) {
            throw new CompressException("try compress a null data");
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(data);
            gzip.finish();
            var result = out.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("Compress data from {}B to {}B.", data.length, result.length);
            }
            return result;
        } catch (IOException e) {
            throw new CompressException("Gzip compress error", e);
        }
    }

    @Override
    public byte[] decompress(byte[] data) {
        if (data == null) {
            throw new CompressException("try decompress a null data");
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(data))) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = gzip.read(buffer);
            out.write(buffer, 0, len);
            var result = out.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("Decompress data from {}B to {}B.", data.length, result.length);
            }
            return result;

        } catch (IOException e) {
            throw new CompressException("Gzip decompress error", e);
        }
    }
}
